package unwrap;

import toxi.geom.Vec3D;
import toxi.math.MathUtils;

class UConnection {

	private USide s;
	private Vec3D pos;
	private float width = 100;
	private float height = 10;

	private Vec3D[] c = new Vec3D[8];
	private Vec3D cc1, cc2;

	UConnection(USide _s, Vec3D _pos) {
		s = _s;
		pos = _pos;

		setAngleCalculatePoints();
	}

	public float getAngle() {
		float newlengthSquared = cc1.distanceToSquared(cc2);
		float widthSquared = 2 * width * width;
		float angle = (float) Math.acos((widthSquared - newlengthSquared)
				/ widthSquared);

		if (isNaN(angle))
			angle = MathUtils.PI;

		float top = c[1].distanceToSquared(c[6]);
		float bottom = c[2].distanceToSquared(c[5]);

		if (top < bottom) {
			angle = MathUtils.TWO_PI - angle;
		}

		return angle;
	}

	private static final boolean isNaN(float v) {
		return (v != v);
	}

	private void setAngleCalculatePoints() {
		float halfHeight = height / 2;
		Vec3D normV = UTriangle.getNormal(s.triangle.a, s.triangle.b,
				s.triangle.c, halfHeight);
		c[0] = pos.add(normV);
		cc1 = UTriangle.getNormal(s.p2, s.p1, c[0], width).addSelf(pos);
		c[1] = cc1.add(normV);
		c[2] = cc1.sub(normV);
		c[3] = pos.sub(normV);

		normV = UTriangle.getNormal(s.neighbor.a, s.neighbor.c, s.neighbor.b,
				halfHeight);
		c[4] = pos.add(normV);
		cc2 = UTriangle.getNormal(s.p2, s.p1, c[4], width).addSelf(pos);
		c[5] = cc2.add(normV);
		c[6] = cc2.sub(normV);
		c[7] = pos.sub(normV);
	}
}
